import os
# import torch
import numpy as np
import shutil
# from torch.autograd import Variable
# from torch import nn
# import torch.nn.functional as F
# from torch.utils.data import Dataset, DataLoader
from PIL import Image, ImageFilter, ImageDraw

# from torchvision import transforms as tfs
# from datetime import datetime
# import matplotlib.pyplot as plt
# from tqdm import tqdm
# import random
# from PIL import Image
Image.MAX_IMAGE_PIXELS = None

image_path = '/home/wangwendan/data/huizhou' #'/remote-home/pxy/data/FUSARMAP2/img'
# label_path = '/remote-home/pxy/data/FUSARMAP2/mask'
image_cropped_save_path = '/home/wangwendan/data/huizhou_cut'#'/remote-home/pxy/data/FUSARMAP2/img_cropped'
# label_cropped_save_path = '/remote-home/pxy/data/FUSARMAP2/mask_cropped'

shutil.rmtree(image_cropped_save_path)
# shutil.rmtree(label_cropped_save_path)

if not os.path.exists(image_cropped_save_path):
    os.makedirs(image_cropped_save_path)
# if not os.path.exists(label_cropped_save_path):
#     os.makedirs(label_cropped_save_path)

crop_width = 1024
crop_height = 1024
step = 0

image_list = os.listdir(image_path)
image_list.sort()
for img_name in image_list:
    print(img_name)
    # mask_name = img_name.replace('.tif', '_mask.tif')
    img_path = os.path.join(image_path, img_name)
    # mask_path = os.path.join(label_path, mask_name)
    img = Image.open(img_path)
    # mask = Image.open(mask_path)
    # mask = Image.open(mask_path)
    print(img.size)
    for i in range(img.size[0] // crop_width):
        for j in range(img.size[1] // crop_height):
            img_cropped = img.crop((i * crop_width, j * crop_height, (i + 1) * crop_width, (j + 1) * crop_height))
            # mask_cropped = mask.crop((i * crop_width, j * crop_height, (i + 1) * crop_width, (j + 1) * crop_height))
            img_cropped_np = np.array(img_cropped)
            # mask_cropped_np = np.array(mask_cropped)
            # print(np.shape(mask_cropped_np))
            # max_np = max(img_cropped_np)
            if np.max(img_cropped_np) <= 0:#判断裁剪后的图像是否为空（全黑）。如果是空图像，则跳过保存操作。
                continue
            # if np.min(mask_cropped_np.sum(axis=2)) < 2:
            #     print('filter black label')
            #     continue

            img_save_name = img_name.split('.tif')[0] + '_' + str(i) + '_' + str(j) + '.tif'
            print(img_save_name)
            img_save_path = os.path.join(image_cropped_save_path, img_save_name)
            img_cropped.save(img_save_path)

            # mask_save_name = mask_name.split('.tif')[0] + '_' + str(i) + '_' + str(j) + '.tif'
            # mask_save_path = os.path.join(label_cropped_save_path, mask_save_name)
            # mask_cropped.save(mask_save_path)
            # print('save_cropped:',img_save_path)



            # mask_cropped = mask.crop((i*crop_width,j*crop_height,(i+1)*crop_width,(j+1)*crop_height))
            # mask_save_name = mask_name.split('.tif')[0]+'_'+str(i)+'_'+str(j)+'.tif'
            # mask_save_path = os.path.join(label_crooped_save_path,mask_save_name)
            # mask_cropped.save(mask_save_path)



# import cv2
#
# # 读取图像
# image = cv2.imread("/home/wangwendan/data/huizhou/huizhou.tif")
#
# # 获取图像的通道数
# channels = cv2.split(image)
# num_channels = len(channels)
#
# # 打印通道数
# print("Number of channels:", num_channels)
#
# # 如果是灰度图像，channels 列表中只有一个元素
# # 如果是 RGB 图像，channels 列表中有三个元素，分别对应 BGR 通道
# # 如果是 RGBA 图像，channels 列表中有四个元素，分别对应 BGRA 通道
# # 判断通道顺序是否是 BGR
# is_bgr = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) is not None
#
# if is_bgr:
#     print("The image format is BGR (Blue, Green, Red).")
# else:
#     print("The image format is not BGR.")
#
#
# # 判断通道顺序是否是 HSV
# is_hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) is not None
#
# if is_hsv:
#     print("The image format is HSV (Hue, Saturation, Value).")
# else:
#     print("The image format is not HSV.")
#
# import imageio
#
# # 读取 TIFF 文件
# tif_data = imageio.imread("/home/wangwendan/data/huizhou/huizhou.tif")
#
# # 获取数据类型信息
# data_type = tif_data.dtype
# print(f"The data type of the TIFF file is: {data_type}")


